const INTERNALS = Symbol('internal request');
/**
 * Extends the [Web Request API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods.
 */ export class RoboRequest extends Request {
    constructor(input, init = {}){
        const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);
        validateURL(url);
        if (input instanceof Request) {
            super(input, init);
        } else {
            super(url, init);
        }
        this[INTERNALS] = {
            params: {},
            raw: {}
        };
    }
    get params() {
        return this[INTERNALS].params;
    }
    get query() {
        const url = new URL(this.url);
        const query = Object.fromEntries(url.searchParams.entries());
        return query;
    }
    get raw() {
        return this[INTERNALS].raw;
    }
    static async from(req, options) {
        const url = `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers.host}${req.url}`;
        const method = req.method || 'GET';
        const headers = new Headers(req.headers);
        let body = options?.body;
        if (!options?.body && ![
            'GET',
            'HEAD'
        ].includes(method)) {
            body = await new Promise((resolve, reject)=>{
                const chunks = [];
                req.on('data', (chunk)=>chunks.push(chunk));
                req.on('end', ()=>resolve(Buffer.concat(chunks)));
                req.on('error', reject);
            });
        }
        const request = new RoboRequest(url, {
            body,
            headers,
            method
        });
        request[INTERNALS].raw = req;
        return request;
    }
}
export function applyParams(request, params) {
    request[INTERNALS].params = params;
}
export function validateURL(url) {
    try {
        return String(new URL(String(url)));
    } catch (error) {
        throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs`, {
            cause: error
        });
    }
}
